package cn.edu.buaa.purain.db;

import java.io.InputStream;
import java.sql.Connection;

public class PurainDBConnectionManager {
	
	public Connection getConnection(String dbName) throws Exception{
		return getConnectionProvider().getConnection(dbName);
	}
	
	private static int isC3p0 = -1;
	
	public IConnectionProvider getConnectionProvider() throws Exception {
	
		if (-1 == isC3p0) {
			if (isC3p0()) {
				isC3p0 = 1;
			}else {
				isC3p0 = 0;
			}
		}
		
		if (1 == isC3p0) {
			return new ConnectionByC3P0();
		}/*else if (isServer()) {
			logger.info("use jndi to get connection...");
			return new ConnectionByJNDI();
		}else */{
			return new ConnectionByXMLProperty();
		}
	
	}
	
	private boolean isC3p0() {
		String c3p0_properties_path = "conf/c3p0.xml";
		
		boolean isC3p0 = false;
		try {
			
			InputStream stream = this.getClass().getClassLoader().getResourceAsStream(c3p0_properties_path);
			if (stream != null) {
				isC3p0 = true;  //and not throw a exception
			}
			
		}catch(Exception ex) {
			//do noting, means not deploy the c3p0 pool
			ex.printStackTrace();
		}
		return isC3p0;
	}
	
	/*private boolean isServer() {
		boolean isServer = false;
		try {
			new InitialContext().lookup("java:comp/env");
			isServer = true;  //not throw a exception
		}catch(Exception ex) {
			//do noting, means not deploy the jndi method
		}
		
		return isServer;
	}*/
}
